import React, { useState, useEffect } from 'react';
import { Avatar } from 'antd-mobile';
import './UserProfileCard.css';
import dayjs from 'dayjs';
import { api } from '../../utils/request';
import { authManager } from '../../utils/auth';

interface UserProfile {
  id: number;
  name: string;
  phone: string;
  avatar: string;
  weight: string;
  height: string;
  birthday: string;
  img: string;
  created_at: string;
  updated_at: string;
}

const UserProfileCard: React.FC = () => {
  const [user, setUser] = useState<UserProfile>({
    id: 1,
    name: '用户名',
    phone: '13800138000',
    avatar: '/image/nv1.jpg',
    weight: '55kg',
    height: '168cm',
    birthday: '1990-01-15',
    img: '/image/nv1.jpg',
    created_at: '',
    updated_at: ''
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUserProfile();
  }, []);

  const fetchUserProfile = async () => {
    try {
      // 获取登录用户信息
      const userInfo = authManager.getUserInfo();
      if (!userInfo || !userInfo.phone) {
        console.log('用户未登录，使用默认数据');
        setLoading(false);
        return;
      }

      console.log('获取登录用户信息:', userInfo);
      
      // 先尝试使用认证API获取当前登录用户的数据
      const response = await api.get('/api/user/profile');
      
      if (response.status === 401) {
        console.log('认证失败，尝试使用手机号API');
        throw new Error('认证失败');
      }
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      // 确保日期格式正确
      if (data.birthday && !/^\d{4}-\d{2}-\d{2}$/.test(data.birthday)) {
        const date = new Date(data.birthday);
        data.birthday = date.toISOString().split('T')[0];
      }
      setUser(data);
    } catch (error) {
      console.error('获取用户资料失败:', error);
      
      // 如果认证API失败，使用登录用户的手机号获取数据
      try {
        const userInfo = authManager.getUserInfo();
        if (userInfo && userInfo.phone) {
          console.log('使用登录用户手机号获取数据:', userInfo.phone);
          const testResponse = await fetch(`/api/user/phone/${userInfo.phone}`);
          if (testResponse.ok) {
            const testData = await testResponse.json();
            // 确保日期格式正确
            if (testData.birthday && !/^\d{4}-\d{2}-\d{2}$/.test(testData.birthday)) {
              const date = new Date(testData.birthday);
              testData.birthday = date.toISOString().split('T')[0];
            }
            setUser(testData);
            return;
          }
        }
      } catch (testError) {
        console.error('使用手机号获取数据失败:', testError);
      }
      
      // 如果所有API都失败，使用默认数据
      console.log('使用默认用户数据');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="user-container">
        <h2 style={{ position: "absolute", top: "2vh", left: "2vh"}}>我的</h2>
        <div className="user-header">
          <div className="loading-placeholder">加载中...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="user-container">
      <h2 style={{ position: "absolute", top: "2vh", left: "2vh"}}>我的</h2>
      <div className="user-header">
        <Avatar
          className="user-avatar"
          src={user.img || user.avatar}
          style={{ '--size': '80px' } as React.CSSProperties}
        />
        <div className="user-info">
          <div className="user-name">{user.name}</div>
        </div>
      </div>
      <div className="user-stats">
        <div className="stat-item">
          <div className="stat-label">体重</div>
          <div className="stat-value">{user.weight}</div>
        </div>
        <div className="stat-item">
          <div className="stat-label">身高</div>
          <div className="stat-value">{user.height}</div>
        </div>
        <div className="stat-item">
          <div className="stat-label">年龄</div> 
          <div className="stat-value">{dayjs().diff(user.birthday, 'year')}岁</div>
        </div>
      </div>
    </div>
  );
};

export default UserProfileCard;